package com.oauth.common.server.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gwtwidgets.server.spring.ServletUtils;

import com.oauth.service.global.beans.OAuthRequestToken;
import com.oauth.service.members.beans.Member;

/**
 * Utility class related to http request and response functionality.
 * 
 * @author asanthan
 * 
 */
public class OAuthRequestUtil {

	private static final String tokenCookie = "ot";
	private static final String tokenSecretCookie = "sot";

	public static Long getMemberId(HttpServletRequest pRequest) {
		Member member = getMember(pRequest);
		return member.getMemberId();
	}

	public static Member getMember(HttpServletRequest pRequest) {
		Member member = (Member) pRequest.getAttribute("member");
		return member;
	}

	public static OAuthRequestToken getOAuthTokenFromCookie(Long applicationId) {
		HttpServletRequest request = ServletUtils.getRequest();
		Cookie[] cookies = request.getCookies();
		String tempCookie = getTokenName(applicationId);
		String tempSecretCookie = getTokenSecretName(applicationId);

		String cookieValue = null;
		String secretCookieValue = null;

		for (Cookie cookie : cookies) {
			if (cookie.getName().equalsIgnoreCase(tempCookie)) {
				cookieValue = cookie.getValue();
			} else if (cookie.getName().equalsIgnoreCase(tempSecretCookie)) {
				secretCookieValue = cookie.getValue();
			}
		}

		if (OAuthStringUtil.isBlank(cookieValue) || OAuthStringUtil.isBlank(secretCookieValue)) {
			return null;
		} else {
			return new OAuthRequestToken(cookieValue, secretCookieValue, null);
		}
	}

	private static String getTokenName(Long applicationId) {
		return tokenCookie + applicationId;
	}

	private static String getTokenSecretName(Long applicationId) {
		return tokenSecretCookie + applicationId;
	}

	public static void deleteTokenCookies(Long applicationId) {
		HttpServletResponse response = ServletUtils.getResponse();
		String tempCookie = getTokenName(applicationId);
		String tempSecretCookie = getTokenSecretName(applicationId);

		Cookie tokenCookie = new Cookie(tempCookie, "");
		tokenCookie.setMaxAge(0);

		Cookie tokenSecretCookie = new Cookie(tempSecretCookie, "");
		tokenSecretCookie.setMaxAge(0);

		response.addCookie(tokenCookie);
		response.addCookie(tokenSecretCookie);
	}

	public static void createTokenCookies(Long applicationId, OAuthRequestToken oauthTokenBean) {
		String tempCookie = getTokenName(applicationId);
		String tempSecretCookie = getTokenSecretName(applicationId);
		HttpServletResponse response = ServletUtils.getResponse();
		Cookie cookie = new Cookie(tempCookie, oauthTokenBean.getToken());
		Cookie secretCookie = new Cookie(tempSecretCookie, oauthTokenBean.getTokenSecret());
		cookie.setPath("/");
		secretCookie.setPath("/");
		response.addCookie(cookie);
		response.addCookie(secretCookie);
	}

}
